package com.xkstream.client.ui.live.fragment;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Bitmap;
import android.graphics.Point;
import android.hardware.Camera;
import android.net.ConnectivityManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.util.Log;
import android.view.TextureView;
import android.view.View;

import com.xkstream.client.R;
import com.xkstream.client.api.API;
import com.xkstream.client.application.Application;
import com.xkstream.client.appmanager.AppManager;
import com.xkstream.client.base.BaseFragment;
import com.xkstream.client.common.CommonDialog;
import com.xkstream.client.entity.User;
import com.xkstream.client.rx.Rxbus;
import com.xkstream.client.ui.live.LiveEndActivity;
import com.xkstream.client.ui.live.LiveHelper;
import com.xkstream.client.ui.live.LiveRoomActivity_V2;
import com.xkstream.client.utils.DeviceUtils;
import com.xkstream.client.utils.LogUtil;
import com.xkstream.client.utils.NetUtil;

import java.util.HashMap;
import java.util.concurrent.TimeUnit;

import butterknife.BindView;
import butterknife.OnClick;
import io.reactivex.disposables.CompositeDisposable;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.WebSocket;
import pushengine.YuerCameraView;
import pushengine.YuerPublisher;


/**
 * Created by xiaoyi on 2017-10-9.
 */

public class LivePreviewFragment_yuer extends BaseFragment implements YuerPublisher.YuerPublisherListener {

    @BindView(R.id.glsurfaceview_camera)
    YuerCameraView glCameraView;

    private boolean isPublishing = false;
    private YuerPublisher mPublisher;


    boolean needRepaire = false;
    private long startTime;
    NetworkReceiver receiver;
    private boolean isFront = true;

    private int gameType;

    @Override
    protected int getLayoutId() {
        return R.layout.fragment_live_preview_yuer;
    }
    CompositeDisposable disposable = new CompositeDisposable();
    int beauty = 3;

    @Override
    public void initViews(View root) {
        registerNetworkBrocastRecevier();
        gameType = getArguments().getInt("gameType");
        int mVideoEncodeQuality = YuerPublisher.YuerVideoEncodeQuality.VIDEO_ENCODE_QUALITY_LOW;
        mPublisher = new YuerPublisher(mVideoEncodeQuality);
        if (mPublisher != null) {
            float mScreenRatio = getScreenRatio();
            mPublisher.setCameraParameter(glCameraView, mScreenRatio);
            mPublisher.setListener(this);
            mPublisher.startCamera();
        }
        prepareLive();

        disposable.add(Rxbus.getDefault().register(String.class)
                .subscribe((s -> {
                    if (s.equals("exit")) {
                        //Bitmap bitmap = glCameraView.getBitmap();
                        Intent intent = new Intent(mActivity, LiveEndActivity.class);
                        intent.putExtra("starttime", startTime);
                        AppManager.getAppManager().finishActivity();
                        mActivity.startActivity(intent);
                    }
                })));
    }


    private void prepareLive() {

        final User user = Application.getUser();
        if (isPublishing) {
            return;
        } else {
            if (mPublisher != null) {
                String videoUrl = API.STREAM_URL + Application.getUser().getAnchor().getStream_id();
                LogUtil.e(TAG, "url  :  " + videoUrl);
//                String videoUrl = "rtmp://pili-publish.wangyuhudong.com/wyds/qn-test?key=e27f6170-a1c7-4f6f-ae0f-1de109b6b1b7";
                LogUtil.e(TAG, videoUrl);
                mPublisher.startPublish(videoUrl);
                isPublishing = true;
            }
        }
    }

    @Override
    public void onPublishStart() {
        startTime = System.currentTimeMillis();
    }

    @Override
    public void onPublishStop() {

    }

    @Override
    public void onPublishException() {
        Log.e(TAG, "onHandleException");
        if (mPublisher != null) {
            mPublisher.stopPublish();
            mPublisher = null;
        }
        showExitDialog(getResources().getString(R.string.live_faild));
    }


    private void showExitDialog(String title) {
        CommonDialog dialog = new CommonDialog(getContext());
        dialog.setListener(() -> {
            ((LiveRoomActivity_V2) getActivity()).anchorOff(0);
           // jumpToActivity(LiveEndActivity.class);
            //getActivity().finish();
            Rxbus.getDefault().post("exit");
        });
        dialog.setTitle(title);

        dialog.setSingleButton();
        dialog.setCancelable(false);
        dialog.setCanceledOnTouchOutside(false);
        dialog.show();
    }

    private class NetworkReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            String NET_CHANGE_ACTION = "android.net.conn.CONNECTIVITY_CHANGE";
            Log.e("NetBroadcastReceiver", "onReceive");
            if (intent.getAction().equals(NET_CHANGE_ACTION)) {
                int netWorkState = NetUtil.getNetworkState(context);
                Log.e("NetBroadcastReceiver", "onReceive" + netWorkState);
                // 接口回调传过去状态的类型
                onNetChange(netWorkState);
            }
        }
    }

    private void onNetChange(int netWorkState) {
        if (isNetConnect(netWorkState) && needRepaire) {
            needRepaire = false;
            prepareLive();
        }
    }

    /**
     * 判断有无网络 。
     *
     * @return true 有网, false 没有网络.
     */
    public boolean isNetConnect(int code) {
        if (code == 1) {
            return true;
        } else if (code == 2) {
            return true;
        } else if (code == 0) {
            return false;
        }
        return false;
    }


    private void registerNetworkBrocastRecevier() {
        receiver = new NetworkReceiver();
        IntentFilter filter = new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION);
        mActivity.registerReceiver(receiver, filter);
    }

    @OnClick({R.id.ivSwitch, R.id.ivClose, R.id.root})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.ivClose:
                mActivity.onBackPressed();
                break;
            case R.id.ivSwitch:
                mPublisher.switchCameraFace((mPublisher.getCamraId() + 1) % Camera.getNumberOfCameras());
                break;
            case R.id.root:
                Rxbus.getDefault().post("onclick");
                break;
        }
    }


    private float getScreenRatio() {
        Point screenSize = new Point();
        getActivity().getWindowManager().getDefaultDisplay().getSize(screenSize);
        float ratio = (float) screenSize.y / screenSize.x;
        return ratio;
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        if (mPublisher != null) {
            mPublisher.stopPublish();
            LogUtil.e(TAG,"onDestroyView stopPublish");
        }
        disposable.clear();
    }
}
